package com.github.ginirohikocha.dbm.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.ginirohikocha.dbm.Address;
import com.github.ginirohikocha.dbm.R;
import com.github.ginirohikocha.dbm.util.HttpUtil;
import com.github.ginirohikocha.dbm.util.JsonUtil;
import com.github.ginirohikocha.dbm.component.mTextWatcher;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private LinearLayout loginMessageBlock;
    private EditText phone, password;
    private TextView loginMessage;
    private ImageView cleanPhone, cleanPwd, showPwd;
    private CheckBox rememberMe;
    private Button login;

    private SharedPreferences workerInfo;

    private boolean isShowPwd = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_act);

        workerInfo = getSharedPreferences("worker", 0);
        //组件初始绑定
        phone = findViewById(R.id.login_phone);//电话号码输入框
        password = findViewById(R.id.login_password);//密码输入框
        loginMessage = findViewById(R.id.login_message);//登陆提示消息
        loginMessageBlock = findViewById(R.id.login_message_block);//登陆提示框
        rememberMe = findViewById(R.id.remember_me);//记住我
        login = findViewById(R.id.login);//登陆按钮
        cleanPhone = findViewById(R.id.login_clean_phone);
        cleanPwd = findViewById(R.id.login_clean_password);
        showPwd = findViewById(R.id.login_show_pwd);
        dialog = new ZLoadingDialog(LoginActivity.this);//登陆加载动画
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.BLACK)//颜色
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .setHintText("登录中...");

        //组件监听绑定
        phone.addTextChangedListener(new mTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    loginMessage.setText(R.string.login_warn_empty_phone);
                    loginMessageBlock.setVisibility(View.VISIBLE);
                    cleanPhone.setVisibility(View.GONE);
                } else {
                    loginMessageBlock.setVisibility(View.GONE);
                    cleanPhone.setVisibility(View.VISIBLE);
                }
            }
        });
        password.addTextChangedListener(new mTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    loginMessage.setText(R.string.login_warn_empty_password);
                    loginMessageBlock.setVisibility(View.VISIBLE);
                    cleanPwd.setVisibility(View.GONE);
                } else {
                    loginMessageBlock.setVisibility(View.GONE);
                    cleanPwd.setVisibility(View.VISIBLE);
                }
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (phone.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
                    loginMessage.setText(R.string.login_warn_empty);
                    loginMessageBlock.setVisibility(View.VISIBLE);
                } else {
                    login(phone.getText().toString(), password.getText().toString());
                }
            }
        });
        cleanPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone.setText("");
            }
        });
        cleanPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                password.setText("");
            }
        });
        showPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPwd) {
                    password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    showPwd.setImageResource(R.drawable.pass_gone);
                } else {
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    showPwd.setImageResource(R.drawable.pass_visuable);
                }
                isShowPwd = !isShowPwd;
            }
        });

        if (workerInfo.getBoolean("rememberMe", false)) {
            rememberMe.setChecked(true);
            phone.setText(workerInfo.getString("mobilephone", ""));
            password.setText(workerInfo.getString("password", ""));
        }
    }

    /**
     * 登陆请求
     * **/
    private void login(final String phone, final String password) {

        final RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), JsonUtil.generateLoginRequestBody(phone, password));
        setLoading(true);
        HttpUtil.sendOkHttpPostRequest(Address.WORKER_LOGIN, requestBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setLoading(false);
                        loginMessage.setText("服务器连接失败，请检查网络状态");
                        loginMessageBlock.setVisibility(View.VISIBLE);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                setLoading(false);
                String responseBody = response.body().string();
                Log.d("登陆", responseBody);
                final JSONObject jsonObject = JSON.parseObject(responseBody);
                //登陆失败
                if (jsonObject == null || !jsonObject.containsKey("code") || jsonObject.getInteger("code") == -1) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!jsonObject.containsKey("code"))
                                loginMessage.setText("服务器连接错误");
                            else
                                loginMessage.setText(jsonObject.getString("msg"));
                            loginMessageBlock.setVisibility(View.VISIBLE);
                        }
                    });
                }
                //登陆成功
                if (jsonObject.getInteger("code") == 1 && jsonObject.getBoolean("succ") && jsonObject.getString("msg").equals("ok")) {
                    SharedPreferences.Editor editor = workerInfo.edit();
                    JSONObject worker = jsonObject.getJSONObject("worker");
                    editor.putInt("id", worker.getInteger("id"));
                    editor.putString("workerNum", worker.getString("workerNum"));
                    editor.putString("workerName", worker.getString("workername"));
                    editor.putString("companyName", jsonObject.getString("company_name"));
                    if (rememberMe.isChecked()) {
                        editor.putBoolean("rememberMe", true);
                        editor.putString("mobilephone", phone);
                        editor.putString("password", password);
                    } else {
                        editor.putBoolean("remembeMme", false);
                        editor.remove("mobilephone");
                        editor.remove("password");
                    }
                    editor.apply();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    LoginActivity.this.finish();
                }
            }
        });
    }

    private ZLoadingDialog dialog;

    private void setLoading(boolean b) {
        if (b) {
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    private long clickTime=0;
    /**
     *  点击两次退出
     * **/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (SystemClock.uptimeMillis() - clickTime <= 1500) {
                //如果两次的时间差＜1s，就不执行操作
            } else {
                //当前系统时间的毫秒值
                clickTime = SystemClock.uptimeMillis();
                Toast.makeText(LoginActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
